﻿using System;
using System.Security.Policy;
using Fetches.Fetch.Dto;
using Fetches.Process.Pipelines.Models;
using Fetches.Process.Utility;
using ServiceStack.OrmLite;

namespace Fetches.Process.Pipelines
{
     public class NovelPipeline:AbstractPipeline
    {
        private ConnectionPool _pool;

        protected override void OnInitial(string site)
        {
            _pool = ConnectionPool.GetInstance(typeof(Site).Name);
            var conn = _pool.GetConnection();
            conn.CreateTableIfNotExists<BookInfo>();
            conn.CreateTableIfNotExists<ChapterInfo>();
            _pool.ReturnConnection(conn);
        }

        protected override void OnProcess(string site, ResultItems result)
        {
            var conn = _pool.GetConnection();
            try
            {
                if (result.Data.ContainsKey("book"))
                {
                    var book = (BookInfo)result.Data["book"]; 
                    if (!conn.Exists<BookInfo>(b=>b.BookId==book.BookId))
                    {
                        conn.Insert(book);
                    }
                }
                if (result.Data.ContainsKey("chapter"))
                {
                    var chapter =(ChapterInfo) result.Data["chapter"];
                    if (!conn.Exists<ChapterInfo>(c => c.BookId==chapter.BookId&&
                                                       c.ChapterId == chapter.ChapterId))
                    {
                        conn.Insert(chapter);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                _pool.ReturnConnection(conn);
            }
        }
    }
}
